<?php

require_once(OC_App::getAppPath('company') . "/lib/helper.php");
JLoader::register("PCompanyModelSubAccounts", OC_App::getAppPath('company') . "/lib/subaccounts.php");

$l = OC_L10N::get('company');
OCP\JSON::callCheck();

if(!PFactory::isMasterUser()) {
   OC_JSON::error(array('data' => array( 'message' => '您无权访问该资源')));
   exit;
}
$post = JRequest::get('post');
$displayname = JRequest::getString("displayname", "");
$username = JRequest::getString("username", "");
$password = JRequest::getString("password", "");
$note = JRequest::getString("note", "");
$permission = JRequest::getVar('permission', array(), '', 'array');
$assignedjobs = JRequest::getVar('assignedjobs', array(), '', 'array');

// Return Success story
try {
   if(!PSession::checkToken('post')) {
      OC_JSON::error(array('data' => array( 'message' => '登录已失效，请重新登录')));
      exit;
   }

   if(!empty($password)) {
      if(!preg_match("/^[^\s]{6,255}$/i", $post["password"])) {
         OC_JSON::error(array('data' => array( 'message' => '请输入有效的密码，至少6个字符，可包含数字、字母或其他字符，不允许使用空格')));
         exit();
      }
      if(!OC_User::setPassword($username, $password)) {
         OC_JSON::error(array('data' => array( 'message' => '修改密码失败！')));
         exit();
      }
   }

   if (!empty($displayname) && !OC_User::setDisplayName($username, $displayname)) {
      OC_JSON::error(array('data' => array( 'message' => '修改姓名失败！')));
      exit();
   }

   $data = array();
   $data['uid'] = $username;
   $data['note'] = $note;
    
   $permissions = PERMISSION_VIEW_ALL | PERMISSION_VIEW_SHARED;
   if (!empty($permission)) {
      foreach ($permission as $p) {
         if ($p & PERMISSION_JOB_CRUD) {
            $permissions |= PERMISSION_JOB_CRUD;
         }
          
         if ($p & PERMISSION_JOB_ADMIN_ALL) {
            $permissions |= PERMISSION_JOB_ADMIN_ALL;
         }
          
         if ($p & PERMISSION_JOB_ADMIN_ASSIGNED) {
            $permissions |= PERMISSION_JOB_ADMIN_ASSIGNED;
         }
      }
   }
   $data['permissions'] = $permissions;
    
   $model = new PCompanyModelSubAccounts;
   
   $old_permissions = $model->getUserPermissions($username);
   
   if (!$model->updateUserExtended($data)) {
      OC_JSON::error(array('data' => array( 'message' => $model->getError() ? $model->getError() : '保存用户失败！')));
      exit();
   }
   
   if (!$model->saveJobManager($username, $permissions, $assignedjobs)) {
      $model->setUserPermissions($username, $old_permissions);
      OC_JSON::error(array('data' => array( 'message' => $model->getError() ? $model->getError() : '系统错误')));
      exit();
   }
 
   OC_JSON::success(array("data" =>array()));

} catch (Exception $exception) {
   OC_JSON::error(array("data" => array( "message" => $l->t($exception->getMessage()))));
}
